
import random, sys, time, re
from zoom import zoomer
from dzstore import Model

from common.models.user import Users

txt_missing_user = 'Email address is incorrect.  Please try again.'

class PasswordAssistant(Model):

    def get_errors(self):
        def verify(valid,message):
            if not valid:
                errors.append(message)

        errors = []
        verify(self.valid_user(),txt_missing_user)

        return errors

#    def get_email(self):
#        user = Users().find_by_loginid(self.email)
#        if user:
#            return user.EMAIL

    def expired(self):
        return time.time() > self.expiry

    def valid_user(self):
        return Users().find_by_email(self.email)

    def set_password(self,password):
        user = Users().find_by_email(self.email)
        if user:
            user.set_password(password)
            user.save()

    def valid_password(self,password):
        user = Users().find_by_email(self.email)
        if user:
            return user.authenticate(password)

    def get_first_name(self):
        user = Users().find_by_email(self.email)
        if user:
            return user.firstname

    def get_username(self):
        user = Users().find_by_email(self.email)
        if user:
            return user.loginid


if __name__ == '__main__':

    import unittest

    class ModuleTests(unittest.TestCase):

        def test_valid_user(self):
            pa = PasswordAssistant(email='user@datazoomer.com')
            assert pa.valid_user()
            pa = PasswordAssistant(email='admin@datazoomer.com')
            assert pa.valid_user()
            pa = PasswordAssistant(email='notauser@datazoomer.com')
            assert not pa.valid_user()

        def test_errors(self):
            pa = PasswordAssistant(email='bogus@datazoomer.com')
            assert pa.errors
            assert pa.errors == [txt_missing_user]
            pa = PasswordAssistant(email='user@datazoomer.com')
            assert not pa.errors

        def test_email(self):
            pa = PasswordAssistant(email='user@datazoomer.com')
            assert pa.email

        def test_set_password(self):
            pa = PasswordAssistant(email='user@datazoomer.com')
            pa.set_password('newpassword')
            assert pa.valid_password('newpassword')
            assert not pa.valid_password('guest')
            pa.set_password('guest')
            assert pa.valid_password('guest')
            assert not pa.valid_password('newpassword')


#            return zoomer.db("update dz_users where loginid=%s set passwd",self.username) and 1 or 0


#        def test_set_password(self):
#            pa = PasswordAssistant()
#            assert pa.valid_user('user')
#            assert pa.valid_user('admin')
#            assert not pa.valid_user('notauser')

    unittest.main()